#!/bin/bash

set -euo pipefail

function retry {
    local retries=$1
    shift

    local count=0
    until "$@"; do
        exit=$?
        wait=$((2 ** count))
        count=$((count + 1))
        if [ $count -lt "$retries" ]; then
            >&2 echo "Retry $count/$retries exited $exit, retrying in $wait seconds..."
            sleep $wait
        else
            >&2 echo "Retry $count/$retries exited $exit, no more retries left."
            return $exit
        fi
    done
    return 0
}

export BUILD_MACHINE_TYPE="n2-standard-4"

# Secrets must be redacted
# https://buildkite.com/docs/pipelines/managing-log-output#redacted-environment-variables
if [[ "$BUILDKITE_PIPELINE_SLUG" == "docs-build-pr" ]];then
    export BUILDKITE_API_TOKEN=$(retry 5 vault kv get -field=value secret/ci/elastic-docs/buildkite_token)
    if [[ ${GITHUB_PR_BASE_REPO:="unset"} == "docs" ]]; then
        # Docs PR require a full rebuild - so let's boost the builds so they don't take 2 hours
        export BUILD_MACHINE_TYPE="n2-highcpu-32"
    fi
elif [[ "$BUILDKITE_PIPELINE_SLUG" == "docs-build" ]];then
    export BUILD_MACHINE_TYPE="n2-highcpu-32"
    export BUILDKITE_API_TOKEN=$(retry 5 vault kv get -field=value secret/ci/elastic-docs/buildkite_token)
elif [[ "$BUILDKITE_PIPELINE_SLUG" == "docs-build-air-gapped" ]] && [[ "$BUILDKITE_STEP_KEY" == "publish-air-gapped-doc" ]]; then
    export DOCKER_USERNAME=$(retry 5 vault kv get -field=username secret/ci/elastic-docs/docker.elastic.co)
    export DOCKER_PASSWORD=$(retry 5 vault kv get -field=password secret/ci/elastic-docs/docker.elastic.co)
fi
